import { wsBaseUrl } from '@/service'
import { useSystemStore, useUserStore } from '@/store'

/**
 * 连接WebSocket
 * @param uid 用户id
 */
export const connectSocket = (uid: number): Promise<string> => {
  const systemStore = useSystemStore()
  const userStore = useUserStore()
  if (systemStore.socketStatus !== 0) {
    return new Promise<string>(async (resolve, reject) => {
      console.log('[Socket]', '开始连接')
      systemStore.socketStatus = 0
      if (!userStore.accessToken) {
        reject("未登录")
        return
      }
      uni.connectSocket({
        url: `${wsBaseUrl}/`,
        header: {
          'content-type': 'application/json',
          'etoken': userStore.accessToken
        },
        method: 'GET',
        success: socketResponse => {
          uni.onSocketOpen(() => {
            systemStore.socketStatus = 1
            resolve(socketResponse)
          })
        },
        fail: err => {
          systemStore.socketStatus = -1
          reject(err)
        }
      })
    })
  } else {
    return new Promise<string>((resolve, reject) => {
      reject('正在连接')
    })
  }
}

// 关闭WebSocket连接
export const closeSocket = (): Promise<any> => {
  return new Promise<any>((resolve, reject) => {
    uni.closeSocket({
      success: socketResponse => {
        if (socketResponse.errMsg === 'closeSocket:ok') {
          resolve(socketResponse)
        } else {
          reject(socketResponse)
        }
      },
      fail: err => {
        reject(err)
      }
    })
  })
}
